package com.jz.main.io.nio;

import java.util.Iterator;
import java.util.ArrayList;
import java.util.List;

public class Iter {
    public static void main(String[] args) {
        ConcreteAggregate aggregate = new ConcreteAggregate();
        aggregate.addItem(1);
        aggregate.addItem(2);
        aggregate.addItem(3);

        Iterator iterator = aggregate.createIterator();

        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }
}

// 定义一个聚合接口
interface Aggregate {
    Iterator<Integer> createIterator();
}

// 具体聚合类，实现了创建具体迭代器的方法
class ConcreteAggregate implements Aggregate {
    private final List<Integer> list = new ArrayList<>();

    public void addItem(Integer item) {
        list.add(item);
    }

    @Override
    public Iterator<Integer> createIterator() {
        return new ConcreteIterator(list);
    }
}


// 具体迭代器类，实现了对 List 集合的遍历
class ConcreteIterator implements Iterator {
    private final List<Integer> list;
    private int position = 0;

    public ConcreteIterator(List<Integer> list) {
        this.list = list;
    }

    @Override
    public boolean hasNext() {
        return position < list.size();
    }

    @Override
    public Integer next() {
        if (hasNext()) {
            return list.get(position++);
        }
        return null;
    }
}
